package cn.itsource.org.controller;

import cn.hutool.Hutool;
import cn.hutool.core.util.RandomUtil;
import cn.itsource.basic.domain.AjaxResult;
import cn.itsource.basic.util.GetUserInfoUtil;
import cn.itsource.basic.util.PhoneUtil;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.User;
import cn.itsource.org.domain.UserAddress;
import cn.itsource.org.mapper.UserAddressMapper;
import cn.itsource.org.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("user")
/**
 * @Api 作用在类上 value 里面填写的是当前类的文档描述
 */
@Api(value = "店铺管理的接口文档",description = "店铺管理的接口文档")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RedisService redisService;

    @Autowired
    UserAddressMapper userAddressMapper;

    @ApiOperation(value = "手机号是否存在", notes = "手机号是否存在")
    @GetMapping("checkphone")
    public AjaxResult exist(String phone){
        return userService.exist(phone);
    }

    @GetMapping("sendmobilecode/{phone}")
    public AjaxResult phoneFile(@PathVariable String phone){
        if(userService.exist(phone).getSuccess()){
            if(redisService.getKeyObjectValue("cpc", String.class) == null) {
                String code = RandomUtil.randomString(4);
                System.out.println("--------------验证码是:"+code+"--------------------");
                redisService.setStringKeyAndValue(phone, code, 5);
                redisService.setStringKeyAndValue("cpc", 0, 1);
                return AjaxResult.me();
            }else{
                return AjaxResult.setMsg("一分钟以内不能连续发送多次");
            }
        }
        return AjaxResult.setMsg("手机号异常");
    }

    @PostMapping("login")
    public AjaxResult login(@RequestBody User user){
        return userService.login(user);
    }
    /**
     * 获取用户地址的接口
     */
    @GetMapping("address")
    public List<UserAddress> findAddressByUserId(){
        Long userId = GetUserInfoUtil.getUserId();
        List<UserAddress> byUserId = userAddressMapper.findByUserId(userId);
        System.out.println(byUserId);
        return byUserId;
    }
}
